import {
    Dispatch
} from 'redux';

import gps from '../../utils/gps';
import Ajax from './../../http';
import * as types from './../types/location';

export default {
    //获取当前的地理位置
    [types.getCurrentLocation]() {
        return async (dispatch: Dispatch) => {
            const {
                longitude = 0,
                latitude = 0
            } = await gps();
            try {
                const _para = {
                    longitude: longitude,
                    latitude: latitude
                }
                const res = await Ajax.get(
                    `location/by/gps`, _para
                )
                dispatch({
                    data: res,
                    type: types.getCurrentLocation
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //根据关键字获取
    [types.getLocationByKeyword](keyword: string) {
        return async (dispatch: Dispatch) => {
            const _para = {
                keyword: keyword
            }
            try {
                const list = await Ajax.get(
                    `locations/by/keyword`, _para
                )
                dispatch({
                    data: list,
                    type: types.getLocationByKeyword
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //获取热门城市
    [types.getHotCity]() {
        return async (dispatch: Dispatch) => {
            try {
                const {
                    hot
                } = await Ajax.get(
                    `location/country/list/orderby/wording`
                )
                const list = (
                    hot.map((item: any) => ({
                        country: item,
                        city: {id: 0},
                        state: {id: 0}
                    }))
                )
                dispatch({
                    data: list,
                    type: types.getHotCity
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }

    }
}